import HModel from '../../index.vue'
import { createApp, h, ref } from 'vue'
import type { DialogProps } from 'element-plus'
export const useHModal = () => {
  const modal = document.createElement('div')
  document.body.appendChild(modal)
  const modalVisible = ref<boolean>(false)
  let app: ReturnType<typeof createApp> | null = null
  const open = (slotVNode: HMODAL.SlotVNode, options?: HMODAL.ModalOptions<DialogProps>) => {
    if (app) {
      app.unmount()
      app = null
    }
    modalVisible.value = true
    const dialog = () =>
      h(
        HModel,
        {
          ...(options as any),
          modelValue: modalVisible.value,
          'onUpdate:modelValue': (val: boolean) => {
            modalVisible.value = val
          },
        },
        {
          default: () => h(slotVNode),
        },
      )
    app = createApp(dialog)
    app.mount(modal)
  }
  const close = () => {
    modalVisible.value = false
  }
  return {
    open,
    close,
  }
}
